package com.atguigu.gmall.realtime.app.func;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.utils.DimUtil;
import com.atguigu.gmall.realtime.utils.ThreadPoolUtil;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.async.ResultFuture;
import org.apache.flink.streaming.api.functions.async.RichAsyncFunction;

import java.util.Collections;
import java.util.concurrent.ExecutorService;

/**
 * Author: Felix
 * Date: 2021/11/10
 * Desc: 开启多个线程，发送异步请求，进行维度关联
 */
public abstract class DimAsyncFunction<T> extends RichAsyncFunction<T, T> implements DimJoinFunction<T>{

    private ExecutorService executorService;

    private String tableName;

    public DimAsyncFunction(String tableName) {
        this.tableName = tableName;
    }

    @Override
    public void open(Configuration parameters) throws Exception {
        executorService = ThreadPoolUtil.getInstance();
    }

    @Override
    public void asyncInvoke(T obj, ResultFuture<T> resultFuture) throws Exception {
        //从线程池中获取线程并执行 ----异步操作
        executorService.submit(
            new Runnable() {
                @Override
                public void run() {
                    //run方法中的代码，就是线程执行的代码---维度关联
                    try {
                        long start = System.currentTimeMillis();
                        //根据流中处理的当前对象obj获取维度的主键
                        String key = getKey(obj);
                        //根据主键获取维度信息
                        JSONObject dimJsonObj = DimUtil.getDimInfo(tableName, key);
                        //将维度信息补充给当期处理的事实对象obj
                        join(obj, dimJsonObj);
                        long end = System.currentTimeMillis();
                        System.out.println("异步维度关联耗时：" + (end - start) + "毫秒");
                        //将异步相应结果向下游传递
                        resultFuture.complete(Collections.singleton(obj));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        );
    }
}
